package com.totcy.baselibrary.download;

import android.annotation.TargetApi;
import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;

import java.io.File;
import java.io.FileNotFoundException;

import static android.R.attr.path;

/**
 * package : cn.adinnet.library.download<br>
 * description:<B>        </B><br>
 * email : cookiexie@adinnet.cn<br>
 * date : 2015/12/4 10:51<br>
 *
 * @author Cookie Xie
 * @version v1.0
 */

public class Downloader {

    private volatile static Downloader instance;

    /**
     * 获取下载单例
     */
    public static Downloader getInstance() {
        if (instance == null) {
            synchronized (Downloader.class) {
                if (instance == null) {
                    instance = new Downloader();
                }
            }
        }
        return instance;
    }

    private Downloader() {
    }

    /**
     * 执行下载任务
     *
     * @param context     上下文，为避免内存泄漏应使用ApplicationContext
     * @param downloadUrl 下载地址
     * @return 如成功下载，返回下载唯一队列ID，未成功返回-1
     * @see #download(Context, String, DownloadConfiguration)
     */
    public long download(Context context, String downloadUrl) {
        return download(context, downloadUrl, null);
    }

    /**
     * 执行下载任务
     *
     * @param context       上下文，为避免内存泄漏应使用<B>ApplicationContext</B>
     * @param downloadUrl   下载地址
     * @param configuration 下载配置，可以配置仅WIFI下载、标题等
     * @return 如成功下载，返回下载唯一队列ID，未成功返回-1
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public long download(Context context, String downloadUrl, DownloadConfiguration configuration) {
        if (TextUtils.isEmpty(downloadUrl)) {
            new FileNotFoundException("下载地址为空，无法下载").printStackTrace();
            return -1;
        }
        if (configuration == null) {
            configuration = new DownloadConfiguration.Builder().defaultConfiguration().build();
        }

        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        //Uri uri = Uri.parse("https://qd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk");
        Uri uri = Uri.parse(downloadUrl);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setAllowedNetworkTypes(configuration.isOnlyWifiDownload() ? DownloadManager.Request.NETWORK_WIFI : ~0)
                .addRequestHeader("Accept-Encoding", "identity")
                .setTitle(configuration.getTitle())//设置下载标题
                .setDescription(configuration.getDescription())//设置描述
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)//设置通知栏，当前为下载过程和下载完成都显示通知栏
                .setVisibleInDownloadsUi(true);//设置下载内容可以被系统下载管理

        if (configuration.getSaveFilePath() == null || configuration.getSaveFilePath().toString().isEmpty()) {
            request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS,
                    configuration.getTitle() + configuration.getVersion() + ".apk");
        } else {
            File path = configuration.getSaveFilePath();
            if (!path.exists()) {
                path.mkdirs();
            }
            File file = new File(path, downloadUrl.substring(downloadUrl.lastIndexOf("/") + 1));
            request.setDestinationUri(Uri.fromFile(file));
        }
        long reference = downloadManager.enqueue(request);
        return reference;
    }
}
